<template>
  <section id="comments" class="comments-section section">
    <h2 class="section-title">
      游客评论 <span class="comment-count">({{ comments.length }}条)</span>
    </h2>

    <div class="comments-container">
      <!-- 评论统计信息 -->
      <div class="comment-stats">
        <div class="stat-item">
          <div class="stat-value">{{ avgRating.toFixed(1) }}</div>
          <div class="stat-stars">
            <div class="star-rating large">
              <span
                v-for="n in 5"
                :key="n"
                :class="{ filled: n <= Math.round(avgRating) }"
                >★</span
              >
            </div>
          </div>
          <div class="stat-label">平均评分</div>
        </div>
        <div class="rating-distribution">
          <div v-for="i in 5" :key="i" class="rating-bar">
            <div class="rating-label">{{ 6 - i }}星</div>
            <div class="rating-progress">
              <div
                class="rating-progress-bar"
                :style="{ width: `${getRatingPercentage(6 - i)}%` }"
              ></div>
            </div>
            <div class="rating-count">{{ getRatingCount(6 - i) }}</div>
          </div>
        </div>
      </div>

      <!-- 撰写评论按钮 -->
      <div v-if="!showCommentForm" class="write-comment-button-wrapper">
        <button @click="showWriteComment" class="btn-write-comment">
          <i class="icon-edit"></i> 撰写评论
        </button>
      </div>

      <!-- 发表评论 -->
      <div v-if="showCommentForm" class="post-comment">
        <div class="comment-form-header">
          <h3 class="comment-form-title">分享你的体验</h3>
          <button @click="hideWriteComment" class="btn-close-form">
            <i class="icon-close"></i>
          </button>
        </div>

        <div class="rating-select">
          <span class="rating-label">评分: </span>
          <div class="star-rating-select">
            <span
              v-for="n in 5"
              :key="n"
              :class="{ filled: n <= newCommentRating }"
              @click="newCommentRating = n"
              @mouseover="hoverRating = n"
              @mouseleave="hoverRating = 0"
              >★</span
            >
          </div>
          <span class="rating-text">{{ getRatingText(newCommentRating) }}</span>
        </div>

        <!-- 添加标题输入框 -->
        <div class="comment-title-input">
          <input
            v-model="newCommentTitle"
            type="text"
            placeholder="添加标题（可选）"
            maxlength="100"
            class="title-input"
          />
          <div class="title-character-count">
            {{ newCommentTitle.length }}/100
          </div>
        </div>

        <!-- 添加旅游类型选择 -->
        <div class="travel-type-select">
          <label class="travel-type-label">旅行类型:</label>
          <div
            class="travel-type-options"
            :class="{ loading: isLoadingTravelTypes }"
          >
            <div v-if="isLoadingTravelTypes" class="loading-indicator">
              加载中...
            </div>
            <template v-else>
              <div
                v-for="type in travelTypes"
                :key="type.id"
                class="type-option"
                :class="{ selected: selectedTravelType === type.id }"
                @click="selectedTravelType = type.id"
              >
                <i v-if="type.icon" :class="type.icon"></i>
                <span>{{ type.name }}</span>
              </div>
              <div v-if="travelTypes.length === 0" class="no-types">
                暂无旅行类型可选
              </div>
            </template>
          </div>
        </div>

        <!-- 图片上传功能 -->
        <div class="image-upload-section">
          <div class="upload-header">
            <span class="upload-title">添加图片</span>
            <span class="upload-count">{{ uploadedImages.length }}/5</span>
          </div>

          <div class="image-preview-container">
            <div
              v-for="(image, index) in uploadedImages"
              :key="index"
              class="image-preview-item"
            >
              <img :src="image.url" alt="预览图片" />
              <button class="btn-remove-image" @click="removeImage(index)">
                <i class="icon-close">×</i>
              </button>
            </div>

            <label
              v-if="uploadedImages.length < 5"
              class="image-upload-btn"
              for="image-upload"
            >
              <i class="icon-image">+</i>
              <span>添加图片</span>
              <input
                id="image-upload"
                type="file"
                accept="image/*"
                multiple
                @change="handleImageUpload"
                style="display: none"
              />
            </label>
          </div>

          <p class="upload-hint">最多上传5张图片，每张不超过5MB</p>
        </div>

        <!-- 富文本编辑器 -->
        <div class="rich-text-editor">
          <div class="editor-toolbar">
            <button
              class="toolbar-btn"
              title="粗体"
              @click="applyFormatting('bold')"
            >
              <i class="icon-bold">B</i>
            </button>
            <button
              class="toolbar-btn"
              title="斜体"
              @click="applyFormatting('italic')"
            >
              <i class="icon-italic">I</i>
            </button>
            <button
              class="toolbar-btn"
              title="下划线"
              @click="applyFormatting('underline')"
            >
              <i class="icon-underline">U</i>
            </button>
            <span class="toolbar-divider"></span>
            <button
              class="toolbar-btn"
              title="项目列表"
              @click="applyFormatting('bullet')"
            >
              <i class="icon-list-ul">•</i>
            </button>
            <button
              class="toolbar-btn"
              title="数字列表"
              @click="applyFormatting('number')"
            >
              <i class="icon-list-ol">1.</i>
            </button>
          </div>

          <textarea
            v-model="newComment"
            placeholder="写下你的评论..."
            class="comment-textarea"
            rows="4"
          ></textarea>

          <div class="comment-form-footer">
            <div
              class="character-count"
              :class="{ 'char-limit-warning': newComment.length > 450 }"
            >
              {{ newComment.length }}/500
            </div>
            <div class="form-buttons">
              <button @click="hideWriteComment" class="btn-cancel-comment">
                取消
              </button>
              <button
                @click="postComment"
                class="btn-post-comment"
                :disabled="!canPostComment || isSubmitting"
              >
                <span v-if="isSubmitting">
                  <i class="icon-spinner"></i> 提交中...
                </span>
                <span v-else> <i class="icon-send"></i> 发表评论 </span>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 评论筛选 -->
      <div class="comment-filters">
        <div class="filter-group">
          <span class="filter-label">筛选:</span>
          <button
            class="filter-button"
            :class="{ active: activeFilter === 'all' }"
            @click="setFilter('all')"
          >
            全部
          </button>
          <button
            class="filter-button"
            :class="{ active: activeFilter === 'positive' }"
            @click="setFilter('positive')"
          >
            好评 (4-5星)
          </button>
          <button
            class="filter-button"
            :class="{ active: activeFilter === 'negative' }"
            @click="setFilter('negative')"
          >
            差评 (1-3星)
          </button>
        </div>
        <div class="filter-group">
          <span class="filter-label">排序:</span>
          <button
            class="filter-button"
            :class="{ active: sortOrder === 'newest' }"
            @click="setSorting('newest')"
          >
            最新
          </button>
          <button
            class="filter-button"
            :class="{ active: sortOrder === 'helpful' }"
            @click="setSorting('helpful')"
          >
            最有帮助
          </button>
        </div>
      </div>

      <!-- 评论列表 -->
      <div class="comments-list" v-if="paginatedComments.length > 0">
        <div
          v-for="comment in paginatedComments"
          :key="comment.id"
          class="comment-item"
          :class="{ featured: comment.featured }"
        >
          <!-- 评论内容 -->
          <div class="comment-header">
            <div class="comment-user">
              <img
                :src="comment.avatar"
                class="comment-avatar"
                :alt="comment.username"
              />
              <div class="comment-user-info">
                <div class="comment-username">{{ comment.username }}</div>
                <div class="comment-meta">
                  <span class="comment-date">{{
                    formatDate(comment.date)
                  }}</span>
                  <span v-if="comment.visitType" class="visit-type">{{
                    comment.visitType
                  }}</span>
                </div>
              </div>
            </div>
            <div class="comment-rating">
              <div class="star-rating">
                <span
                  v-for="n in 5"
                  :key="n"
                  :class="{ filled: n <= comment.rating }"
                  >★</span
                >
              </div>
            </div>
          </div>

          <div class="comment-content">
            <div v-if="comment.featured" class="featured-badge">
              <i class="icon-star"></i> 精选点评
            </div>
            <h4 v-if="comment.title" class="comment-title">
              {{ comment.title }}
            </h4>
            <p>{{ comment.text }}</p>
            <div
              v-if="comment.images && comment.images.length > 0"
              class="comment-images"
            >
              <div
                v-for="(image, imgIndex) in comment.images"
                :key="imgIndex"
                class="comment-image"
              >
                <img
                  :src="image"
                  @click="viewImage(image)"
                  alt="用户上传图片"
                />
              </div>
            </div>
            <div class="comment-actions">
              <button
                @click="toggleLike(comment)"
                class="btn-like"
                :class="{ liked: comment.userLiked }"
              >
                <i class="icon-like"></i>
                <span>有帮助 ({{ comment.likes }})</span>
              </button>
              <button @click="toggleReply(comment)" class="btn-reply">
                <i class="icon-reply"></i> 回复
              </button>
              <button class="btn-report"><i class="icon-flag"></i> 举报</button>
            </div>
          </div>

          <!-- 回复输入框 -->
          <div v-if="comment.showReply" class="reply-form">
            <textarea
              v-model="comment.replyText"
              placeholder="写下你的回复..."
              class="reply-textarea"
              rows="2"
              :disabled="comment.isSubmitting"
            ></textarea>
            <div class="reply-form-footer">
              <button
                @click="hideReply(comment)"
                class="btn-cancel-reply"
                :disabled="comment.isSubmitting"
              >
                取消
              </button>
              <button
                @click="postReply(comment)"
                class="btn-post-reply"
                :disabled="
                  !comment.replyText ||
                  comment.replyText.trim() === '' ||
                  comment.isSubmitting
                "
              >
                <span v-if="comment.isSubmitting">
                  <i class="icon-spinner"></i> 提交中...
                </span>
                <span v-else>发表回复</span>
              </button>
            </div>
          </div>

          <!-- 回复列表 -->
          <div
            v-if="comment.replies && comment.replies.length > 0"
            class="replies-list"
          >
            <div class="replies-header">
              <span class="replies-count"
                >{{ comment.replies.length }}条回复</span
              >
            </div>
            <div
              v-for="reply in comment.replies.slice(
                0,
                comment.showAllReplies ? comment.replies.length : 2
              )"
              :key="reply.id"
              class="reply-item"
              :class="{ official: reply.isOfficial }"
            >
              <div class="reply-header">
                <div class="reply-user">
                  <img
                    :src="reply.avatar"
                    class="reply-avatar"
                    :alt="reply.username"
                  />
                  <div class="reply-user-info">
                    <div class="reply-username">
                      {{ reply.username }}
                      <span v-if="reply.isOfficial" class="official-tag"
                        >官方回复</span
                      >
                    </div>
                    <div class="reply-date">{{ formatDate(reply.date) }}</div>
                  </div>
                </div>
              </div>
              <div class="reply-content">
                <p>{{ reply.text }}</p>
                <div class="reply-actions">
                  <button
                    @click="toggleLike(reply)"
                    class="btn-like"
                    :class="{ liked: reply.userLiked }"
                  >
                    <i class="icon-like"></i>
                    <span>{{ reply.likes }}</span>
                  </button>
                </div>
              </div>
            </div>
            <button
              v-if="comment.replies.length > 2"
              @click="toggleShowAllReplies(comment)"
              class="btn-show-replies"
            >
              <i
                :class="
                  comment.showAllReplies
                    ? 'icon-chevron-up'
                    : 'icon-chevron-down'
                "
              ></i>
              {{
                comment.showAllReplies
                  ? "收起回复"
                  : `查看全部${comment.replies.length}条回复`
              }}
            </button>
          </div>
        </div>
      </div>

      <!-- 无评论状态 -->
      <div v-else class="no-comments">
        <div class="no-comments-icon">📝</div>
        <p>暂无评论，来留下第一条评论吧！</p>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="comments-pagination">
        <button
          @click="prevPage"
          :disabled="currentPage === 1"
          class="page-button"
        >
          <i class="icon-chevron-left"></i> 上一页
        </button>

        <div class="page-numbers">
          <button
            v-if="currentPage > 3"
            @click="currentPage = 1"
            class="page-number"
          >
            1
          </button>

          <span v-if="currentPage > 3">...</span>

          <button
            v-for="page in visiblePageNumbers"
            :key="page"
            @click="currentPage = page"
            class="page-number"
            :class="{ active: currentPage === page }"
          >
            {{ page }}
          </button>

          <span v-if="currentPage < totalPages - 2">...</span>

          <button
            v-if="currentPage < totalPages - 2"
            @click="currentPage = totalPages"
            class="page-number"
          >
            {{ totalPages }}
          </button>
        </div>

        <button
          @click="nextPage"
          :disabled="currentPage === totalPages"
          class="page-button"
        >
          下一页 <i class="icon-chevron-right"></i>
        </button>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted, watch, defineProps } from "vue";
import {
  getTravelTypes,
  addComment,
  addCommentReply,
  getCommentsByCityId,
  likeComment,
  likeReply,
  uploadCommentImages,
} from "@/api/cityComment";
import { addExp } from "@/api/user";
import { useStore } from "vuex";

// 定义 props
const props = defineProps({
  cityId: {
    type: [Number, String],
    default: null,
  },
  commentType: {
    type: String,
    default: null,
  },
});

// 在 setup 中获取 store
const store = useStore();

// 响应式数据
const newComment = ref(""); // 新评论内容
const newCommentTitle = ref(""); // 新评论标题
const newCommentRating = ref(5); // 新评论的评分
const comments = ref([]); // 所有评论
const currentPage = ref(1); // 当前页码
const commentsPerPage = ref(5); // 每页显示的评论数量
const isLoading = ref(false);
const activeFilter = ref("all"); // 当前筛选 - all, positive, negative
const sortOrder = ref("newest"); // 排序方式 - newest, helpful
const showCommentForm = ref(false); // 控制评论表单的显示状态
const hoverRating = ref(0); // 用于鼠标悬停时的评分显示
const uploadedImages = ref([]); // 存储上传的图片
const travelTypes = ref([]); // 存储从后端获取的旅游类型
const selectedTravelType = ref(null); // 当前选择的旅游类型ID
const isLoadingTravelTypes = ref(false); // 加载旅游类型状态
const travelTypeNameMap = ref({});
const isSubmitting = ref(false); // 评论提交状态

// 计算可见的页码
const visiblePageNumbers = computed(() => {
  const delta = 1; // 当前页前后显示的页码数
  let range = [];
  const totalPagesValue = totalPages.value;
  const currentPageValue = currentPage.value;

  const startPage = Math.max(1, currentPageValue - delta);
  const endPage = Math.min(totalPagesValue, currentPageValue + delta);

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

// 计算平均评分
const avgRating = computed(() => {
  if (comments.value.length === 0) return 0;

  const sum = comments.value.reduce(
    (acc, comment) => acc + (comment.rating || 0),
    0
  );
  return sum / comments.value.length;
});

// 筛选后的评论
const filteredComments = computed(() => {
  let result = [...comments.value];

  // 应用筛选
  if (activeFilter.value === "positive") {
    result = result.filter((comment) => comment.rating >= 4);
  } else if (activeFilter.value === "negative") {
    result = result.filter((comment) => comment.rating < 4);
  }

  // 应用排序
  if (sortOrder.value === "newest") {
    result.sort((a, b) => new Date(b.date) - new Date(a.date));
  } else if (sortOrder.value === "helpful") {
    result.sort((a, b) => b.likes - a.likes);
  }

  return result;
});

// 分页后的评论
const paginatedComments = computed(() => {
  const start = (currentPage.value - 1) * commentsPerPage.value;
  const end = start + commentsPerPage.value;
  return filteredComments.value.slice(start, end);
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredComments.value.length / commentsPerPage.value) || 1;
});

// 更新验证逻辑
const canPostComment = computed(() => {
  return (
    newComment.value.trim() !== "" &&
    newComment.value.length <= 500 &&
    newCommentRating.value > 0
  );
});

// 根据旅行类型ID获取名称
const getTravelTypeName = (typeId) => {
  // 如果已经有映射，直接返回
  if (travelTypeNameMap.value[typeId]) {
    return travelTypeNameMap.value[typeId];
  }

  // 查找旅行类型
  const foundType = travelTypes.value.find((t) => t.id === typeId);
  if (foundType) {
    travelTypeNameMap.value[typeId] = foundType.name;
    return foundType.name;
  }

  // 默认返回"自由行"
  return "自由行";
};

// 根据评分返回对应的评价文字
const getRatingText = (rating) => {
  switch (rating) {
    case 1:
      return "很糟糕";
    case 2:
      return "不满意";
    case 3:
      return "一般";
    case 4:
      return "满意";
    case 5:
      return "非常满意";
    default:
      return "";
  }
};

// 处理图片上传
const handleImageUpload = (event) => {
  const files = event.target.files;

  if (!files.length) return;

  // 限制上传数量
  const remainingSlots = 5 - uploadedImages.value.length;
  const filesToProcess = Math.min(files.length, remainingSlots);

  for (let i = 0; i < filesToProcess; i++) {
    const file = files[i];

    // 检查文件大小（5MB限制）
    if (file.size > 5 * 1024 * 1024) {
      alert(`图片 ${file.name} 超过5MB，请选择较小的图片`);
      continue;
    }

    // 创建本地预览URL
    const reader = new FileReader();
    reader.onload = (e) => {
      uploadedImages.value.push({
        file: file,
        url: e.target.result,
      });
    };
    reader.readAsDataURL(file);
  }

  // 清除input以允许重复选择相同的文件
  event.target.value = "";
};

// 移除已上传的图片
const removeImage = (index) => {
  uploadedImages.value.splice(index, 1);
};

// 显示评论表单
const showWriteComment = () => {
  // 检查用户是否登录
  if (!store.getters.isLoggedIn) {
    alert("请先登录后再发表评论");
    return;
  }

  showCommentForm.value = true;
};

// 隐藏评论表单
const hideWriteComment = () => {
  showCommentForm.value = false;
  // 重置评论框内容
  newComment.value = "";
  newCommentTitle.value = "";
  newCommentRating.value = 5;
  // 重置为默认旅游类型
  selectedTravelType.value =
    travelTypes.value.length > 0 ? travelTypes.value[0].id : null;
  uploadedImages.value = [];
};

// 富文本编辑器功能
const applyFormatting = (format) => {
  // 获取textarea元素
  const textarea = document.querySelector(".comment-textarea");
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  const selectedText = newComment.value.substring(start, end);

  let formattedText = "";

  // 应用不同的格式
  switch (format) {
    case "bold":
      formattedText = `**${selectedText}**`;
      break;
    case "italic":
      formattedText = `*${selectedText}*`;
      break;
    case "underline":
      formattedText = `__${selectedText}__`;
      break;
    case "bullet":
      formattedText = selectedText
        .split("\n")
        .map((line) => `• ${line}`)
        .join("\n");
      break;
    case "number":
      formattedText = selectedText
        .split("\n")
        .map((line, i) => `${i + 1}. ${line}`)
        .join("\n");
      break;
    default:
      formattedText = selectedText;
  }

  // 更新文本内容
  newComment.value =
    newComment.value.substring(0, start) +
    formattedText +
    newComment.value.substring(end);

  // 设置选择区域为插入的格式文本
  setTimeout(() => {
    textarea.focus();
    textarea.selectionStart = start;
    textarea.selectionEnd = start + formattedText.length;
  }, 0);
};

// 获取旅游类型列表
const fetchTravelTypes = async () => {
  isLoadingTravelTypes.value = true;
  try {
    const response = await getTravelTypes();
    // 调整以适配后端返回的数据结构
    if (response.state === 0 && response.data) {
      travelTypes.value = response.data;
      // 如果有旅游类型，默认选择第一个
      if (travelTypes.value.length > 0) {
        selectedTravelType.value = travelTypes.value[0].id;
      }
      console.log("获取到旅游类型:", travelTypes.value);
    } else {
      console.error("获取旅游类型格式错误:", response);
      travelTypes.value = [];
    }
  } catch (error) {
    console.error("获取旅游类型失败:", error);
    travelTypes.value = [];
  } finally {
    isLoadingTravelTypes.value = false;
  }
};

// 组件挂载时的处理
onMounted(() => {
  console.log("CommentSection mounted, cityId:", props.cityId);

  // 获取旅游类型列表
  fetchTravelTypes();

  // 如果有cityId，则加载该城市的评论
  if (props.cityId) {
    fetchComments();
  } else {
    // 没有cityId时，显示一些演示评论
    loadDemoComments();
  }
});

// 监听 cityId 变化
watch(
  () => props.cityId,
  (newVal) => {
    if (newVal) {
      console.log("cityId changed, new value:", newVal);
      fetchComments();
    }
  }
);

// 加载评论数据
const fetchComments = async () => {
  isLoading.value = true;
  try {
    // 使用真实API获取评论数据
    const response = await getCommentsByCityId(props.cityId, props.commentType);

    if (response.state === 0 && response.data) {
      // 将后端数据转换为组件需要的格式
      comments.value = response.data.map((item) => {
        // 构建评论对象
        const commentObj = {
          id: item.comment.id,
          username: item.user.userName || item.user.realName,
          avatar:
            item.user.avatar ||
            "https://randomuser.me/api/portraits/lego/1.jpg",
          rating: item.comment.rating,
          title: item.comment.title,
          text: item.comment.content,
          date: new Date(item.comment.createdAt),
          likes: item.comment.likes,
          userLiked: item.likesCount > 0, // 用户是否点赞
          visitType: getTravelTypeName(item.comment.travelTypeId),
          featured: item.comment.isFeatured,
          showReply: false,
          showAllReplies: false,
          // 处理图片
          images: item.images.map((img) => img.imageUrl),
          // 处理回复
          replies: item.replies.map((reply) => ({
            id: reply.reply.id,
            username: reply.user.userName || reply.user.realName,
            avatar:
              reply.user.avatar ||
              "https://randomuser.me/api/portraits/lego/2.jpg",
            text: reply.reply.content,
            date: new Date(reply.reply.createdAt),
            likes: reply.reply.likes,
            userLiked: reply.likesCount > 0,
            isOfficial: reply.reply.isOfficial,
          })),
        };
        return commentObj;
      });

      console.log("成功加载评论数据:", comments.value.length);
    } else {
      console.error("获取评论数据格式错误:", response);
      comments.value = [];
    }
  } catch (error) {
    console.error("获取评论失败:", error);
    comments.value = [];
  } finally {
    isLoading.value = false;
  }
};

// 获取某个评分的数量
const getRatingCount = (rating) => {
  return comments.value.filter(
    (comment) => Math.round(comment.rating) === rating
  ).length;
};

// 获取某个评分的百分比
const getRatingPercentage = (rating) => {
  if (comments.value.length === 0) return 0;
  return (getRatingCount(rating) / comments.value.length) * 100;
};

// 设置筛选条件
const setFilter = (filter) => {
  activeFilter.value = filter;
  currentPage.value = 1;
};

// 设置排序方式
const setSorting = (sort) => {
  sortOrder.value = sort;
  currentPage.value = 1;
};

// 查看图片
const viewImage = (image) => {
  // 这里可以实现查看大图的功能
  console.log("View image:", image);
};

// 加载演示评论
const loadDemoComments = () => {
  comments.value = [
    {
      id: 1,
      username: "旅行爱好者",
      avatar: "https://randomuser.me/api/portraits/women/44.jpg",
      rating: 5,
      title: "美不胜收的旅行体验",
      text: "这个城市真是太美了，特别是那些古老的建筑和街道，充满了历史感。强烈推荐大家来这里旅游！我们在这里度过了美好的五天，每天都有新的发现。当地人非常友好，而且餐厅的食物味道很棒。",
      date: new Date("2023-12-25"),
      likes: 42,
      userLiked: false,
      visitType: "家庭出游",
      featured: true,
      images: [
        "https://images.unsplash.com/photo-1501594907352-04cda38ebc29",
        "https://images.unsplash.com/photo-1522093537031-3ee69e6b1746",
      ],
      showReply: false,
      showAllReplies: false,
      replies: [
        {
          id: 101,
          username: "摄影师小王",
          avatar: "https://randomuser.me/api/portraits/men/32.jpg",
          text: "完全同意！我上个月刚去过，拍了好多照片。春天去最美，花开满城，景色宜人。你有去过城南的那个历史博物馆吗？非常值得一去！",
          date: new Date("2023-12-26"),
          likes: 15,
          userLiked: false,
        },
        {
          id: 102,
          username: "背包客",
          avatar: "https://randomuser.me/api/portraits/women/68.jpg",
          text: "请问有没有推荐的住宿地点？准备下个月去，想找一个位置好一点的酒店。",
          date: new Date("2023-12-28"),
          likes: 3,
          userLiked: false,
        },
        {
          id: 103,
          username: "旅行爱好者",
          avatar: "https://randomuser.me/api/portraits/women/44.jpg",
          text: "@背包客 市中心有很多不错的青旅，性价比高，而且地理位置优越。我住的是城西的阳光酒店，离景点很近，交通也方便。",
          date: new Date("2023-12-29"),
          likes: 8,
          userLiked: false,
        },
      ],
    },
    {
      id: 2,
      username: "美食探索者",
      avatar: "https://randomuser.me/api/portraits/men/86.jpg",
      rating: 4,
      title: "美食天堂，但价格偏高",
      text: "当地的美食真是令人难忘，尤其是那家老字号的面馆，味道真的太棒了！不过物价有点高，预算紧张的朋友需要做好准备。总体来说还是很推荐，特别是对美食感兴趣的朋友。",
      date: new Date("2023-12-20"),
      likes: 28,
      userLiked: false,
      visitType: "独自旅行",
      featured: false,
      images: ["https://images.unsplash.com/photo-1504674900247-0877df9cc836"],
      showReply: false,
      showAllReplies: false,
      replies: [
        {
          id: 201,
          username: "本地吃货",
          avatar: "https://randomuser.me/api/portraits/women/24.jpg",
          text: "如果你喜欢那家面馆，也可以试试东区的那家小饭馆，价格更亲民，味道也很棒！",
          date: new Date("2023-12-21"),
          likes: 19,
          userLiked: false,
        },
        {
          id: 202,
          username: "城市管理员",
          avatar: "https://randomuser.me/api/portraits/men/45.jpg",
          text: "感谢您的反馈！我们会考虑在旅游手册中增加更多不同价位的餐厅推荐，以满足不同游客的需求。",
          date: new Date("2023-12-22"),
          likes: 5,
          isOfficial: true,
          userLiked: false,
        },
      ],
    },
    {
      id: 3,
      username: "历史爱好者",
      avatar: "https://randomuser.me/api/portraits/men/22.jpg",
      rating: 5,
      title: "历史底蕴深厚的城市",
      text: "这座城市的博物馆收藏非常丰富，展示了从古至今的历史变迁。参观需要预约，大家记得提前安排。我在这里呆了三天，感觉时间还不够用，很多地方都值得深入了解。",
      date: new Date("2023-12-15"),
      likes: 35,
      userLiked: false,
      visitType: "朋友结伴",
      featured: false,
      showReply: false,
      showAllReplies: false,
      replies: [],
    },
    {
      id: 4,
      username: "自然探险家",
      avatar: "https://randomuser.me/api/portraits/women/90.jpg",
      rating: 4.5,
      title: "城市周边的自然风光也很美",
      text: "除了城区的历史景点，我强烈推荐大家到郊外的山区走一走。那里空气清新，景色宜人，而且还能参加各种户外活动。我们租了自行车环湖骑行，是此行最美好的记忆之一。",
      date: new Date("2023-11-30"),
      likes: 27,
      userLiked: false,
      visitType: "情侣出游",
      featured: false,
      images: [
        "https://images.unsplash.com/photo-1501785888041-af3ef285b470",
        "https://images.unsplash.com/photo-1476514525535-07fb3b4ae5f1",
        "https://images.unsplash.com/photo-1469854523086-cc02fe5d8800",
      ],
      showReply: false,
      showAllReplies: false,
      replies: [],
    },
    {
      id: 5,
      username: "预算旅行者",
      avatar: "https://randomuser.me/api/portraits/men/55.jpg",
      rating: 3,
      title: "景色不错但消费偏高",
      text: "城市景色确实很美，但整体消费水平偏高，特别是在旅游旺季。住宿、餐饮和景点门票都不便宜。建议大家提前做好预算规划，并尝试使用一些折扣券或旅游套餐。",
      date: new Date("2023-11-15"),
      likes: 41,
      userLiked: false,
      visitType: "商务旅行",
      featured: false,
      showReply: false,
      showAllReplies: false,
      replies: [
        {
          id: 501,
          username: "城市旅游局",
          avatar: "https://randomuser.me/api/portraits/men/75.jpg",
          text: "感谢您的宝贵意见！我们会继续优化旅游体验，同时增加更多不同价位的选择。欢迎您再次光临我们的城市，下次可以选择淡季来访，价格会相对亲民一些。",
          date: new Date("2023-11-16"),
          likes: 12,
          isOfficial: true,
          userLiked: false,
        },
      ],
    },
    {
      id: 6,
      username: "文化体验者",
      avatar: "https://randomuser.me/api/portraits/women/33.jpg",
      rating: 5,
      title: "深入了解当地文化的好地方",
      text: "这次旅行最大的收获是参加了当地的文化体验活动，学习了传统工艺制作，还参加了民俗表演。这些活动让我对这座城市的文化有了更深入的理解，非常推荐给想要深度旅行的朋友们。",
      date: new Date("2023-10-25"),
      likes: 38,
      userLiked: false,
      visitType: "教育旅行",
      featured: true,
      images: ["https://images.unsplash.com/photo-1516307365426-bea591f05011"],
      showReply: false,
      showAllReplies: false,
      replies: [],
    },
    {
      id: 7,
      username: "周末短途游",
      avatar: "https://randomuser.me/api/portraits/men/41.jpg",
      rating: 4,
      title: "周末度假的理想选择",
      text: "作为周末短途游的目的地，这座城市非常合适。从邻近城市开车过来只需要2小时，景点相对集中，很容易安排行程。我们在这里度过了愉快的周末，感觉很充实但又不会太赶。",
      date: new Date("2023-10-10"),
      likes: 22,
      userLiked: false,
      visitType: "周末度假",
      featured: false,
      showReply: false,
      showAllReplies: false,
      replies: [],
    },
    {
      id: 8,
      username: "妈妈游记",
      avatar: "https://randomuser.me/api/portraits/women/63.jpg",
      rating: 4.5,
      title: "带孩子出游的好选择",
      text: "这座城市对家庭游非常友好，有许多适合儿童的博物馆和游乐设施。我们带着5岁和8岁的孩子一起来，他们玩得很开心，尤其喜欢科技馆和动物园。餐厅也普遍提供儿童餐和高椅。",
      date: new Date("2023-09-20"),
      likes: 32,
      userLiked: false,
      visitType: "家庭出游",
      featured: false,
      showReply: false,
      showAllReplies: false,
      replies: [
        {
          id: 801,
          username: "旅行达人",
          avatar: "https://randomuser.me/api/portraits/women/28.jpg",
          text: "完全同意！我上个月也带孩子去了，城北的那个主题乐园特别适合小朋友，下次可以试试。",
          date: new Date("2023-09-22"),
          likes: 8,
          userLiked: false,
        },
      ],
    },
    {
      id: 9,
      username: "老年旅行者",
      avatar: "https://randomuser.me/api/portraits/men/67.jpg",
      rating: 3.5,
      title: "适合慢节奏游览，但缺少无障碍设施",
      text: "这个城市有很多值得参观的地方，节奏也不会太快，适合我们这些老年人慢慢游览。但是有些景点的无障碍设施不够完善，坡道和电梯较少，对行动不便的游客不太友好。",
      date: new Date("2023-09-05"),
      likes: 29,
      userLiked: false,
      visitType: "银发族旅行",
      featured: false,
      showReply: false,
      showAllReplies: false,
      replies: [
        {
          id: 901,
          username: "城市管理员",
          avatar: "https://randomuser.me/api/portraits/men/45.jpg",
          text: "感谢您的反馈！我们正在逐步改善各景点的无障碍设施，已将您的建议记录下来，会在下一阶段的改造中予以考虑。",
          date: new Date("2023-09-06"),
          likes: 15,
          isOfficial: true,
          userLiked: false,
        },
      ],
    },
    {
      id: 10,
      username: "摄影爱好者",
      avatar: "https://randomuser.me/api/portraits/men/29.jpg",
      rating: 5,
      title: "摄影天堂，光线和景色绝佳",
      text: "作为一名摄影爱好者，我被这座城市的光线和景色深深吸引。无论是黄昏时分的古建筑，还是清晨的城市公园，都能拍出令人满意的照片。特别推荐河边的观景台，日落时分景色无与伦比。",
      date: new Date("2023-08-15"),
      likes: 45,
      userLiked: false,
      visitType: "摄影之旅",
      featured: false,
      images: [
        "https://images.unsplash.com/photo-1493246507139-91e8fad9978e",
        "https://images.unsplash.com/photo-1470093851219-69951fcbb533",
      ],
      showReply: false,
      showAllReplies: false,
      replies: [],
    },
    {
      id: 11,
      username: "美食博主",
      avatar: "https://randomuser.me/api/portraits/women/79.jpg",
      rating: 4.5,
      title: "舌尖上的城市之旅",
      text: "这座城市的美食值得专门为它来一次旅行！从街头小吃到米其林餐厅，从传统美食到创新料理，种类繁多且品质上乘。我尤其推荐城南的美食街，那里有许多当地特色小吃，价格也很亲民。",
      date: new Date("2023-08-03"),
      likes: 37,
      userLiked: false,
      visitType: "美食之旅",
      featured: false,
      images: ["https://images.unsplash.com/photo-1414235077428-338989a2e8c0"],
      showReply: false,
      showAllReplies: false,
      replies: [],
    },
    {
      id: 12,
      username: "背包客小李",
      avatar: "https://randomuser.me/api/portraits/men/81.jpg",
      rating: 2,
      title: "景色不错但服务有待提高",
      text: "虽然城市景色优美，但我在这次旅行中遇到了一些服务问题。部分景点的工作人员态度冷漠，公共交通也不够便捷。希望城市管理部门能够改进这些问题，提升整体旅游体验。",
      date: new Date("2023-07-22"),
      likes: 19,
      userLiked: false,
      visitType: "背包旅行",
      featured: false,
      showReply: false,
      showAllReplies: false,
      replies: [
        {
          id: 1201,
          username: "城市旅游局",
          avatar: "https://randomuser.me/api/portraits/men/75.jpg",
          text: "非常抱歉您在旅行中遇到了不愉快的体验。我们正在加强对服务人员的培训，并优化公共交通线路。感谢您的宝贵意见，这对我们改进工作非常重要。",
          date: new Date("2023-07-23"),
          likes: 7,
          isOfficial: true,
          userLiked: false,
        },
        {
          id: 1202,
          username: "另一位游客",
          avatar: "https://randomuser.me/api/portraits/women/42.jpg",
          text: "我上个月去的时候也有类似的感受，特别是在主要景点，服务质量确实有待提高。",
          date: new Date("2023-07-24"),
          likes: 3,
          userLiked: false,
        },
      ],
    },
  ];
};

// 修改发表评论函数，实现与后端交互
const postComment = async () => {
  if (!canPostComment.value) return;

  // 检查用户是否登录
  if (!store.getters.isLoggedIn) {
    alert("请先登录后再发表评论");
    return;
  }

  const userId = store.state.userInfo?.userId;
  if (!userId) {
    alert("用户信息不完整，请重新登录");
    return;
  }
  let ctp = props.commentType;

  // 准备评论数据
  const commentData = {
    cityId: props.cityId,
    userId: userId,
    rating: newCommentRating.value,
    travelTypeId: selectedTravelType.value,
    title: newCommentTitle.value || null,
    content: newComment.value,
    isFeatured: false,
    likes: 0,
    status: "pending",
    type: ctp, // 默认状态，可能需要审核
  };

  try {
    // 显示加载状态
    isSubmitting.value = true;

    // 调用API提交评论
    const response = await addComment(commentData);

    if (response && response.state === 0 && response.data) {
      console.log("评论提交成功:", response.data);

      if (!store.state.experience.comment) {
        let userId = store.state.userInfo.userId;
        let exp = store.state.commentExperience;
        // alert(exp)
        const response1 = await addExp(userId, exp);
        alert(response1.state);

        if (response1 && response1.state === 0) {
          alert("评论成功，经验值增加" + exp);
          store.commit("setCommentExperience");
        }
      }

      const newCommentId = response.data.id;

      // 如果有图片，上传图片
      if (uploadedImages.value.length > 0) {
        try {
          // 获取文件对象数组
          const files = uploadedImages.value.map((img) => img.file);

          // 调用上传图片API
          const uploadResponse = await uploadCommentImages(newCommentId, files);

          if (uploadResponse && uploadResponse.state === 0) {
            console.log("图片上传成功:", uploadResponse.data);
          } else {
            console.error("图片上传失败:", uploadResponse);
            alert("评论已发表，但图片上传失败，请稍后重试");
          }
        } catch (uploadError) {
          console.error("图片上传请求失败:", uploadError);
          alert("评论已发表，但图片上传失败，请稍后重试");
        }
      }

      // 重新获取评论列表，以显示新发布的评论
      await fetchComments();

      // 重置并隐藏评论表单
      resetCommentForm();

      // 显示成功提示
      alert("评论发表成功，等待审核");
    } else {
      console.error("评论提交失败:", response);
      alert(response?.message || "评论提交失败，请稍后重试");
    }
  } catch (error) {
    console.error("评论提交请求失败:", error);
    alert("网络请求失败，请检查网络连接");
  } finally {
    // 重置提交状态
    isSubmitting.value = false;
  }
};

// 用于模拟评论添加成功的函数
const simulateAddComment = () => {
  // 获取选中的旅游类型名称
  const selectedType = travelTypes.value.find(
    (t) => t.id === selectedTravelType.value
  );
  const visitTypeName = selectedType ? selectedType.name : "自由行";

  // 模拟图片URL
  const imageUrls = uploadedImages.value.map((img) => img.url);

  // 添加到评论列表
  comments.value.unshift({
    id: Date.now(),
    username: "游客用户",
    avatar: "https://randomuser.me/api/portraits/lego/1.jpg",
    rating: newCommentRating.value,
    title: newCommentTitle.value || null,
    text: newComment.value,
    date: new Date(),
    likes: 0,
    userLiked: false,
    visitType: visitTypeName,
    featured: false,
    images: imageUrls.length > 0 ? imageUrls : null,
    showReply: false,
    showAllReplies: false,
    replies: [],
  });
};

// 重置评论表单
const resetCommentForm = () => {
  newComment.value = "";
  newCommentTitle.value = "";
  newCommentRating.value = 5;
  // 默认选择第一个旅游类型
  selectedTravelType.value =
    travelTypes.value.length > 0 ? travelTypes.value[0].id : null;
  uploadedImages.value = [];
  showCommentForm.value = false;
  // 确保显示第一页，以便看到刚发布的评论
  currentPage.value = 1;
  activeFilter.value = "all";
  sortOrder.value = "newest";
  // 重置提交状态
  isSubmitting.value = false;
};

// 点赞功能
const toggleLike = async (item) => {
  // 检查用户是否登录
  if (!store.getters.isLoggedIn) {
    alert("请先登录后再点赞");
    return;
  }

  try {
    const userId = store.state.userInfo?.userId;
    if (!userId) {
      alert("用户信息不完整，请重新登录");
      return;
    }

    let response;

    // 判断是评论还是回复
    if ("text" in item && !("title" in item)) {
      // 这是一条回复
      response = await likeReply(item.id, userId);
    } else {
      // 这是一条评论
      response = await likeComment(item.id, userId);
    }

    // 如果后端请求成功，更新前端UI
    if (response && response.state === 0) {
      // 切换点赞状态
      if (item.userLiked) {
        item.likes -= 1;
      } else {
        item.likes += 1;
      }
      item.userLiked = !item.userLiked;

      console.log(`${item.userLiked ? "点赞" : "取消点赞"} ID:${item.id} 成功`);
    } else {
      // 后端返回错误
      console.error("点赞操作失败:", response);
      alert("点赞操作失败，请稍后再试");
    }
  } catch (error) {
    console.error("点赞请求失败:", error);
    alert("网络请求失败，请检查网络连接");
  }
};

// 显示/隐藏回复输入框
const toggleReply = (comment) => {
  // 检查用户是否登录
  if (!store.getters.isLoggedIn) {
    alert("请先登录后再回复");
    return;
  }

  comment.showReply = !comment.showReply;
  comment.replyText = "";
};

// 隐藏回复框
const hideReply = (comment) => {
  comment.showReply = false;
  comment.replyText = "";
};

// 发表回复
const postReply = async (comment) => {
  if (!comment.replyText || comment.replyText.trim() === "") return;

  // 检查用户是否登录
  if (!store.getters.isLoggedIn) {
    alert("请先登录后再回复");
    return;
  }

  const userId = store.state.userInfo?.userId;
  if (!userId) {
    alert("用户信息不完整，请重新登录");
    return;
  }

  try {
    // 设置提交状态
    comment.isSubmitting = true;

    // 准备回复数据
    const replyData = {
      commentId: comment.id,
      userId: userId,
      content: comment.replyText.trim(),
      likes: 0,
      isOfficial: false, // 普通用户发布的回复
      status: "pending", // 可能需要审核
      type: this.comment_type,
    };

    // 调用API发送回复
    const response = await addCommentReply(replyData);

    if (response && response.state === 0) {
      console.log("回复发表成功:", response.data);
      store.commit("setCommentExperience");

      if (!store.state.experience.comment) {
        let userId = store.state.userInfo.userId;
        let exp = store.state.commentExperience;
        // alert(exp)
        const response1 = await addExp(userId, exp);
        alert(response1.state);

        if (response1 && response1.state === 0) {
          alert("评论成功，经验值增加" + exp);
          store.commit("setCommentExperience");
        }
      }

      // 确保replies数组存在
      if (!comment.replies) {
        comment.replies = [];
      }

      // 添加新回复到前端显示
      const newReply = {
        id: response.data?.id || Date.now(),
        username:
          store.state.userInfo.userName || store.state.userInfo.realName,
        avatar:
          store.state.userInfo.avatar ||
          "https://randomuser.me/api/portraits/lego/2.jpg",
        text: comment.replyText,
        date: new Date(),
        likes: 0,
        userLiked: false,
        isOfficial: false,
      };

      comment.replies.push(newReply);

      // 清空并关闭回复框
      comment.showReply = false;
      comment.replyText = "";

      // 可选：显示成功提示
      alert("回复发表成功");
    } else {
      console.error("发表回复失败:", response);
      alert(response?.message || "发表回复失败，请稍后重试");
    }
  } catch (error) {
    console.error("回复请求失败:", error);
    alert("网络请求失败，请检查网络连接");
  } finally {
    // 重置提交状态
    comment.isSubmitting = false;
  }
};

// 展开/折叠回复
const toggleShowAllReplies = (comment) => {
  comment.showAllReplies = !comment.showAllReplies;
};

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--;
};

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++;
};

// 日期格式化
const formatDate = (date) => {
  if (!date) return "";

  const d = new Date(date);
  const now = new Date();
  const diffTime = Math.abs(now - d);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  // 如果是今天
  if (d.toDateString() === now.toDateString()) {
    return "今天";
  }

  // 如果是昨天
  const yesterday = new Date();
  yesterday.setDate(now.getDate() - 1);
  if (d.toDateString() === yesterday.toDateString()) {
    return "昨天";
  }

  // 如果是7天内
  if (diffDays <= 7) {
    return `${diffDays}天前`;
  }

  // 其他情况返回完整日期
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(d.getDate()).padStart(2, "0")}`;
};
</script>

<style scoped>
/* 评论区样式 */
.comments-section {
  background-color: #f9f9f9;
  margin-top: 40px;
  padding: 40px 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 28px;
  margin-bottom: 40px;
  color: #333;
  text-align: center;
  font-weight: 700;
  position: relative;
}

.section-title::after {
  content: "";
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background: linear-gradient(to right, #3498db, #2ecc71);
  border-radius: 3px;
}

.comment-count {
  font-size: 18px;
  color: #777;
  font-weight: normal;
  margin-left: 10px;
}

.comments-container {
  max-width: 1100px;
  margin: 0 auto;
}

/* 评论统计信息 */
.comment-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  background-color: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
}

.stat-stars {
  margin: 10px 0;
}

.star-rating.large {
  font-size: 24px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.rating-distribution {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  margin-left: 40px;
}

.rating-bar {
  display: flex;
  align-items: center;
  margin: 4px 0;
}

/* 评分选择组件样式优化 */
.rating-select {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.rating-label {
  font-size: 16px;
  margin-right: 10px;
  color: #333;
}

.star-rating-select {
  font-size: 30px;
  letter-spacing: 5px;
  color: #ddd;
  cursor: pointer;
  display: inline-block;
}

.star-rating-select span {
  position: relative;
  transition: all 0.2s;
}

.star-rating-select span:hover,
.star-rating-select span.filled {
  color: #f1c40f;
  transform: scale(1.2);
}

.star-rating-select span:hover ~ span {
  color: #ddd;
}

.rating-text {
  margin-left: 15px;
  font-size: 14px;
  color: #3498db;
  font-weight: 500;
}

/* 新增标题输入框样式 */
.comment-title-input {
  position: relative;
  margin-bottom: 20px;
  width: 97%;
}

.title-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-family: inherit;
  font-size: 16px;
  font-weight: 500;
  transition: border-color 0.3s;
}

.title-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.title-character-count {
  position: absolute;
  right: 10px;
  bottom: -20px;
  font-size: 12px;
  color: #7f8c8d;
}

/* 图片上传组件样式 */
.image-upload-section {
  margin: 20px 0;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
}

.upload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.upload-title {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.upload-count {
  font-size: 14px;
  color: #7f8c8d;
}

.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 10px;
}

.image-preview-item {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  border: 1px solid #ddd;
}

.image-preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.btn-remove-image {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
  border: none;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  opacity: 0;
  transition: opacity 0.2s;
}

.image-preview-item:hover .btn-remove-image {
  opacity: 1;
}

.image-upload-btn {
  width: 100px;
  height: 100px;
  border: 2px dashed #bdc3c7;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #7f8c8d;
  transition: all 0.2s;
}

.image-upload-btn:hover {
  border-color: #3498db;
  color: #3498db;
  background-color: rgba(52, 152, 219, 0.05);
}

.icon-image {
  font-size: 24px;
  margin-bottom: 5px;
}

.upload-hint {
  font-size: 12px;
  color: #95a5a6;
  margin-top: 5px;
}

.rating-progress {
  flex-grow: 1;
  background-color: #eee;
  height: 12px;
  border-radius: 6px;
  overflow: hidden;
  margin: 0 10px;
}

.rating-progress-bar {
  height: 100%;
  background: linear-gradient(to right, #3498db, #2ecc71);
}

.rating-count {
  width: 30px;
  font-size: 14px;
  color: #555;
}

/* 旅游类型选择样式 */
.travel-type-select {
  margin-bottom: 20px;
}

.travel-type-label {
  display: block;
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
}

.travel-type-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-height: 120px;
  overflow-y: auto;
  padding: 5px 0;
}

.travel-type-options.loading {
  justify-content: center;
  align-items: center;
  min-height: 60px;
}

.loading-indicator {
  color: #7f8c8d;
  font-size: 14px;
}

.type-option {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
  color: #555;
}

.type-option:hover {
  background-color: #e9ecef;
  border-color: #ccc;
}

.type-option.selected {
  background-color: #3498db;
  color: white;
  border-color: #3498db;
}

.no-types {
  padding: 10px;
  color: #7f8c8d;
  font-size: 14px;
  font-style: italic;
}

/* 评论筛选 */
.comment-filters {
  display: flex;
  justify-content: space-between;
  margin: 30px 0;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  margin: 5px 0;
}

.filter-label {
  color: #555;
  margin-right: 10px;
  font-size: 14px;
}

.filter-button {
  background: none;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 8px 16px;
  margin: 0 5px;
  cursor: pointer;
  font-size: 14px;
  color: #555;
  transition: all 0.2s;
}

.filter-button:hover {
  background-color: #f0f0f0;
}

.filter-button.active {
  background-color: #3498db;
  border-color: #3498db;
  color: white;
}

/* 撰写评论按钮 */
.write-comment-button-wrapper {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.btn-write-comment {
  padding: 14px 32px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
  display: flex;
  align-items: center;
  gap: 10px;
}

.btn-write-comment:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(52, 152, 219, 0.4);
}

.btn-write-comment .icon-edit:before {
  content: "✎";
  font-size: 18px;
}

/* 评论表单 */
.post-comment {
  margin-bottom: 30px;
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08);
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.comment-form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.comment-form-title {
  font-size: 20px;
  color: #2c3e50;
  margin: 0;
}

.btn-close-form {
  background: none;
  border: none;
  cursor: pointer;
  color: #7f8c8d;
  font-size: 18px;
  transition: color 0.2s;
}

.btn-close-form:hover {
  color: #34495e;
}

.btn-close-form .icon-close:before {
  content: "×";
}

/* 富文本编辑器 */
.rich-text-editor {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.editor-toolbar {
  display: flex;
  gap: 5px;
  background-color: #f8f9fa;
  padding: 8px 12px;
  border-bottom: 1px solid #ddd;
}

.toolbar-btn {
  background: none;
  border: none;
  border-radius: 4px;
  padding: 6px 10px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-weight: bold;
  color: #555;
}

.toolbar-btn:hover {
  background-color: #e9ecef;
}

.toolbar-divider {
  height: 24px;
  width: 1px;
  background-color: #ddd;
  margin: 0 5px;
}

.comment-textarea {
  width: 100%;
  padding: 15px;
  border: none;
  border-radius: 0;
  resize: vertical;
  font-family: inherit;
  min-height: 120px;
  font-size: 15px;
  transition: border-color 0.3s;
  background-color: #fff;
}

.comment-textarea:focus {
  outline: none;
}

.comment-form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #f8f9fa;
  border-top: 1px solid #ddd;
}

.form-buttons {
  display: flex;
  gap: 10px;
}

.btn-cancel-comment {
  padding: 10px 18px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 6px;
  color: #555;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-cancel-comment:hover {
  background-color: #e9ecef;
}

/* 评论按钮的加载状态样式 */
.btn-post-comment .icon-spinner {
  display: inline-block;
  width: 14px;
  height: 14px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
  margin-right: 5px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 无评论状态 */
.no-comments {
  text-align: center;
  padding: 50px 0;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.no-comments-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.no-comments p {
  color: #7f8c8d;
  font-size: 18px;
}

/* 评论列表 */
.comments-list {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.comment-item {
  padding: 25px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s, box-shadow 0.2s;
}

.comment-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.comment-item.featured {
  border-left: 4px solid #f1c40f;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.comment-user {
  display: flex;
  align-items: center;
}

.comment-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.comment-username {
  font-weight: 700;
  color: #2c3e50;
  font-size: 16px;
  margin-bottom: 3px;
}

.comment-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.comment-date {
  color: #7f8c8d;
  font-size: 13px;
}

.visit-type {
  font-size: 12px;
  background-color: #f8f9fa;
  color: #555;
  padding: 3px 8px;
  border-radius: 12px;
}

.comment-rating {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.star-rating {
  color: #ddd;
  font-size: 18px;
  letter-spacing: 2px;
}

.star-rating .filled {
  color: #f1c40f;
}

.featured-badge {
  display: inline-block;
  background-color: #fff8e1;
  color: #f1c40f;
  font-size: 12px;
  font-weight: 600;
  padding: 5px 10px;
  border-radius: 4px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 6px;
  width: fit-content;
}

.comment-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #2c3e50;
}

.comment-content p {
  margin-bottom: 15px;
  line-height: 1.6;
  color: #333;
}

.comment-images {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin: 15px 0;
}

.comment-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
}

.comment-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.comment-image img:hover {
  transform: scale(1.05);
}

.comment-actions {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}

.btn-like,
.btn-reply,
.btn-report {
  display: flex;
  align-items: center;
  gap: 6px;
  background: none;
  border: none;
  color: #777;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.2s;
}

.btn-like:hover,
.btn-reply:hover {
  color: #3498db;
}

.btn-report:hover {
  color: #e74c3c;
}

.btn-like.liked {
  color: #3498db;
}

/* 回复输入框 */
.reply-form {
  margin-top: 20px;
  margin-left: 25px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.reply-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  resize: vertical;
  font-family: inherit;
  margin-bottom: 15px;
  font-size: 14px;
}

.reply-form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-cancel-reply {
  padding: 8px 15px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  color: #555;
  cursor: pointer;
}

.btn-post-reply {
  padding: 8px 15px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-post-reply:hover {
  background-color: #2980b9;
}

.btn-post-reply:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

/* 提交中旋转图标 */
.icon-spinner {
  display: inline-block;
  width: 12px;
  height: 12px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
  margin-right: 5px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 禁用按钮时的样式 */
.btn-post-reply:disabled,
.btn-cancel-reply:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 禁用文本框时的样式 */
.reply-textarea:disabled {
  background-color: #f0f0f0;
  cursor: not-allowed;
}

/* 回复列表 */
.replies-list {
  margin-top: 20px;
  margin-left: 25px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.replies-header {
  padding: 0 0 8px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 5px;
}

.replies-count {
  color: #555;
  font-size: 14px;
  font-weight: 500;
}

.reply-item {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.reply-item.official {
  background-color: #ebf8ff;
  border-left: 3px solid #3498db;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.reply-avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.reply-username {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.official-tag {
  background-color: #3498db;
  color: white;
  font-size: 11px;
  font-weight: 500;
  padding: 2px 6px;
  border-radius: 3px;
  margin-left: 8px;
}

.reply-date {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 2px;
}

.reply-content p {
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

.reply-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.btn-show-replies {
  background: none;
  border: none;
  color: #3498db;
  cursor: pointer;
  margin-top: 10px;
  align-self: flex-start;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 分页 */
.comments-pagination {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.page-button {
  padding: 10px 15px;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s;
}

.page-button:hover:not(:disabled) {
  background-color: #f8f9fa;
  border-color: #3498db;
  color: #3498db;
}

.page-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 8px;
  align-items: center;
}

.page-number {
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  border: 1px solid #ddd;
  background-color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.page-number:hover:not(.active) {
  border-color: #3498db;
  color: #3498db;
}

.page-number.active {
  background-color: #3498db;
  color: white;
  border-color: #3498db;
}

@media (max-width: 768px) {
  .comment-stats {
    flex-direction: column;
    gap: 20px;
  }

  .rating-distribution {
    margin-left: 0;
    width: 100%;
  }

  .comment-filters {
    flex-direction: column;
    gap: 15px;
  }

  .filter-group {
    width: 100%;
    overflow-x: auto;
    padding-bottom: 5px;
  }

  .comment-user-info {
    max-width: 150px;
  }

  .comment-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .comment-images {
    justify-content: center;
  }
}
</style>
